package com.jijuxie.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jijuxie.common.exception.ServiceException;
import com.jijuxie.message.domain.Message;
import com.jijuxie.message.mapper.MessageMapper;
import com.jijuxie.message.service.IMessageService;
import com.jijuxie.message.websocket.WebSocketServer;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendSystemMessage(Long userId, String title, String content) {
        if (userId == null) {
            throw new ServiceException("用户ID不能为空");
        }
        if (title == null || title.isEmpty()) {
            throw new ServiceException("消息标题不能为空");
        }
        if (content == null || content.isEmpty()) {
            throw new ServiceException("消息内容不能为空");
        }

        Message message = new Message();
        message.setUserId(userId);
        message.setTitle(title);
        message.setContent(content);
        message.setType("1");
        message.setReadStatus("0");
        message.setDelFlag(0);
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());
        save(message);

        // 实时推送
        try {
            webSocketServer.sendSystemMessage(userId, content);
        } catch (Exception e) {
            log.error("消息推送失败：{}", e.getMessage());
        }
    }

    @Override
    public void sendAppointmentMessage(Long userId, Long appointmentId) {
        // TODO: 根据预约ID获取预约信息，生成通知内容
        sendSystemMessage(userId, "预约通知", "您有新的预约消息");
    }

    @Override
    public void sendDealMessage(Long userId, Long dealId) {
        // TODO: 根据成交ID获取成交信息，生成通知内容
        sendSystemMessage(userId, "成交通知", "您有新的成交消息");
    }

    @Override
    public Page<Message> selectMyMessagePage(Page<Message> page, Message message) {
        if (message == null) {
            message = new Message();
        }
        return page(page, new LambdaQueryWrapper<Message>()
                .eq(Message::getUserId, StpUtil.getLoginIdAsLong())
                .eq(message.getType() != null, Message::getType, message.getType())
                .eq(message.getReadStatus() != null, Message::getReadStatus, message.getReadStatus())
                .orderByDesc(Message::getCreateTime));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markRead(Long messageId) {
        Message message = getById(messageId);
        if (message == null) {
            throw new ServiceException("消息不存在");
        }
        message.setReadStatus("1");
        message.setUpdateTime(LocalDateTime.now());
        updateById(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markAllRead() {
        baseMapper.updateAllRead(StpUtil.getLoginIdAsLong());
    }

    @Override
    public Integer getUnreadCount() {
        return baseMapper.selectUnreadCount(StpUtil.getLoginIdAsLong());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMessage(Long messageId) {
        Message message = getById(messageId);
        if (message == null) {
            throw new ServiceException("消息不存在");
        }
        message.setDelFlag(1);
        message.setUpdateTime(LocalDateTime.now());
        updateById(message);
    }
}
